Public Class BrIntegration

    'TODO...

    'Public Enum ReadWriteMode
    '    Read
    '    Edit
    '    None
    '    Unknown
    'End Enum

    'Private Shared providers As TaxonNamesInterface.UserProvider()

    'Private Shared readMode As ReadWriteMode = ReadWriteMode.Unknown

    'Public Shared ReadOnly Property UserProviders() As TaxonNamesInterface.UserProvider()
    '    Get
    '        If providers Is Nothing Then
    '            providers = NamesDataAccess.UserData.GetUserProviders(TaxonNamesInterface.SessionState.CurrentUser.IdAsInt)
    '        End If
    '        Return providers
    '    End Get
    'End Property

    'Public Shared Function GetSystemProviderImport() As TaxonNamesInterface.ProviderImport
    '    Dim pi As TaxonNamesInterface.ProviderImport

    '    Try
    '        'Get latest system ProviderImport for the latest UserProvider
    '        'UserProviders are ordered from newest to oldest
    '        'ProviderImports are also ordered from newest to oldest
    '        For Each up As TaxonNamesInterface.UserProvider In UserProviders
    '            If up.Provider.IsEditor Then
    '                pi = up.ProviderImports(0)
    '                Exit For
    '            End If
    '        Next
    '    Catch ex As Exception
    '    End Try

    '    Return pi
    'End Function


    'Public Shared Function GetReadWriteMode() As ReadWriteMode
    '    If readMode = ReadWriteMode.Unknown Then
    '        Dim sysPI As TaxonNamesInterface.ProviderImport = GetSystemProviderImport()
    '        If sysPI Is Nothing Then
    '            readMode = ReadWriteMode.Read
    '        Else
    '            readMode = ReadWriteMode.Edit
    '        End If
    '    End If
    '    Return readMode
    'End Function

    '#Region "Concepts"

    '    ''' <summary>
    '    ''' Updates the concept from the linked provider concepts.
    '    ''' </summary>
    '    ''' <param name="ConceptPk"></param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshConceptData(ByVal ConceptPk As Integer)
    '        'ConceptData.RefreshConceptData(ConceptPk, SessionState.CurrentUser.Login)

    '        'get concept 
    '        Dim ds As DataSet = ConceptData.GetConceptDs(ConceptPk)
    '        Dim updateC As DataRow = ds.Tables(0).Rows(0)

    '        'get provider Cs
    '        Dim providerCs As DataSet = ConceptData.GetProviderConceptRecords(ConceptPk)

    '        'calculate consensus values
    '        For Each cm As ConceptMapping In BrProviderConcepts.ConceptMappings
    '            Dim sc As String = cm.MappingSourceCol
    '            If sc = "PCAccordingToId" Then sc = "PRReferenceFk"
    '            Dim val As Object = GetConsensusValue(providerCs, sc)
    '            If sc = "PCName1" And val Is DBNull.Value Then
    '                'just use namefull of name
    '                Dim nm As Name = NameData.GetName(Nothing, updateC("ConceptName1Fk"))
    '                val = nm.NameFull
    '            End If
    '            updateC(cm.MappingDestCol) = val
    '        Next

    '        'update concept
    '        ConceptData.UpdateConcept(New Concept(updateC, updateC("ConceptPk").ToString), SessionState.CurrentUser.Login)

    '    End Sub


    '    Private Shared Function GetConsensusValue(ByVal pcrs As DataSet, ByVal sourceCol As String) As Object
    '        Dim vals As New Hashtable
    '        Dim sysVal As Object = DBNull.Value

    '        For Each row As DataRow In pcrs.Tables(0).Rows
    '            If row("ProviderIsEditor") AndAlso Not row.IsNull(sourceCol) Then
    '                sysVal = row(sourceCol)
    '                Exit For
    '            End If

    '            If vals.ContainsKey(row(sourceCol)) Then
    '                vals(row(sourceCol)) += 1
    '            Else
    '                If row(sourceCol) IsNot DBNull.Value Then vals.Add(row(sourceCol), 1)
    '            End If
    '        Next

    '        If sysVal IsNot DBNull.Value Then Return sysVal

    '        'get majority value (must be > majority than next common value, ie if equal number of 2 diff values, then there is no consensus)
    '        Dim val As Object = DBNull.Value
    '        Dim maxNum As Integer = 0
    '        Dim hasEqual As Boolean = False
    '        For Each key As Object In vals.Keys
    '            If vals(key) > maxNum Then
    '                maxNum = vals(key)
    '                val = key
    '                hasEqual = False
    '            ElseIf vals(key) = maxNum Then
    '                hasEqual = True
    '            End If
    '        Next

    '        If hasEqual Then Return DBNull.Value

    '        Return val
    '    End Function

    '    Public Shared Sub RefreshConceptRelationshipData(ByVal conceptRelationshipGuid As String)
    '        'ConceptData.RefreshConceptRelationshipData(conceptRelationshipGuid, SessionState.CurrentUser.Login)

    '        'get concept relationship
    '        Dim ds As DataSet = ConceptData.GetConceptRelationshipDs(conceptRelationshipGuid)
    '        If ds.Tables.Count = 0 OrElse ds.Tables(0).Rows.Count = 0 Then Return

    '        Dim updateCR As DataRow = ds.Tables(0).Rows(0)

    '        'get provider CRs
    '        Dim providerCRs As DataSet = ConceptData.GetProviderConceptRelationshipsForCR(conceptRelationshipGuid)

    '        'calculate consensus values
    '        For Each crm As ConceptRelationshipMapping In BrProviderConcepts.ConceptRelationshipMappings
    '            Dim sc As String = crm.ConceptRelationshipMappingSourceCol
    '            If sc = "PCRConcept1Id" Then sc = "PCConcept1Fk"
    '            If sc = "PCRConcept2Id" Then sc = "PCConcept2Fk"
    '            Dim val As Object = GetConsensusValue(providerCRs, sc)
    '            updateCR(crm.ConceptRelationshipMappingDestCol) = val
    '        Next

    '        'update cr
    '        ConceptData.UpdateConceptRelationship(New ConceptRelationship(updateCR, updateCR("ConceptRelationshipGuid")), SessionState.CurrentUser.Login)
    '    End Sub

    '#End Region

    '#Region "Names"

    '    ''' <summary>
    '    ''' Refreshes Name record data
    '    ''' Update relationships links (rank, parent, preferred, basiony, homonym, etc ...)
    '    ''' based on the existing relationships for the specified ProviderName (if provided).
    '    ''' Then update all Name data from source ProviderName records
    '    ''' </summary>
    '    ''' <param name="refreshList">List of RefreshData - NameGuids (keys) and ProviderName Pks (value) for Names to update</param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshNameData(ByVal refreshList As List(Of RefreshData), ByVal includeConcepts As Boolean)
    '        For Each rf As RefreshData In refreshList
    '            'rank
    '            NameData.LinkNameRank(rf.NameGuid, SessionState.CurrentUser.Login)

    '            'update relationships (if provider pk exists - for inserted/new names)
    '            If rf.IsNew Then
    '                NameData.UpdateNameRelationships(rf.NameGuid, rf.PNPk, SessionState.CurrentUser.Login)
    '            Else
    '                'otherwise update provider name relationships for existing names
    '                NameData.UpdateProviderNameRelationships(rf.PNPk, SessionState.CurrentUser.Login)
    '            End If

    '            'refresh Name data
    '            RefreshNameData(rf.NameGuid, includeConcepts)
    '        Next
    '    End Sub

    '    Private Shared Function GetConsensusValue(ByVal provRecords As DataSet, ByVal sourceCol As String) As Object
    '        Dim vals As New Hashtable
    '        Dim sysVal As Object = DBNull.Value

    '        For Each row As DataRow In provRecords.Tables(0).Rows
    '            If row("ProviderIsEditor") AndAlso Not row.IsNull(sourceCol) Then
    '                sysVal = row(sourceCol)
    '                Exit For
    '            End If

    '            If vals.ContainsKey(row(sourceCol)) Then
    '                vals(row(sourceCol)) += 1
    '            Else
    '                If row(sourceCol) IsNot DBNull.Value Then vals.Add(row(sourceCol), 1)
    '            End If
    '        Next

    '        If sysVal IsNot DBNull.Value Then Return sysVal

    '        'get majority value (must be > majority than next common value, ie if equal number of 2 diff values, then there is no consensus)
    '        Dim val As Object = DBNull.Value
    '        Dim maxNum As Integer = 0
    '        Dim hasEqual As Boolean = False
    '        For Each key As Object In vals.Keys
    '            If vals(key) > maxNum Then
    '                maxNum = vals(key)
    '                val = key
    '                hasEqual = False
    '            ElseIf vals(key) = maxNum Then
    '                hasEqual = True
    '            End If
    '        Next

    '        'always return something for canonical name
    '        If sourceCol = "PNNameCanonical" Then Return val

    '        If hasEqual Then Return DBNull.Value

    '        'if authors is null then see if we can get a corrected author
    '        If sourceCol = "PNNameAuthors" Then

    '        End If

    '        Return val
    '    End Function

    '    Private Shared Function CalculateMatchScore(ByVal concName As DataRow, ByVal provName As DataRow) As Integer
    '        Dim match As Integer = 0

    '        Dim tally As Integer = 0
    '        Dim count As Integer = 0

    '        For Each nm As NameMapping In BrProviderNames.NameMappings
    '            If provName(nm.NameMappingSourceCol).ToString <> concName(nm.NameMappingDestCol).ToString Then
    '                tally += nm.MatchWeighting
    '            End If
    '            count += 1
    '        Next

    '        match = 100 - (tally * 100 / BrProviderNames.NameMappings.Count)

    '        Return match
    '    End Function


    '    ''' <summary>
    '    ''' Refresh the Name data from the source Provider Name records.
    '    ''' Only the fields are refreshed.  The rank is not updated.
    '    ''' Parent and Preferred Fks are updated from the Concepts.
    '    ''' </summary>
    '    ''' <param name="nameGuid"></param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshNameData(ByVal nameGuid As String, ByVal includeConcepts As Boolean)

    '        'get name
    '        Dim ds As DataSet = NameData.GetNameDs(Nothing, nameGuid)
    '        If ds.Tables(0).Rows.Count = 0 Then Return 'has been deprecated

    '        Dim updateName As DataRow = ds.Tables(0).Rows(0)

    '        'get provider names
    '        Dim providerNames As DataSet = NameData.GetProviderNameRecords(nameGuid)

    '        Dim updatedPns As DataSet = providerNames.Clone
    '        For Each pn As DataRow In providerNames.Tables(0).Rows
    '            Dim newPn As DataRow = NameData.UpdateProviderNameRelationships(pn("PNPk"), SessionState.CurrentUser.Login)
    '            If newPn IsNot Nothing Then
    '                updatedPns.Tables(0).ImportRow(newPn)
    '            Else
    '                updatedPns.Tables(0).ImportRow(pn) 'is a system provider name
    '            End If
    '        Next

    '        'calculate consensus values
    '        For Each nm As NameMapping In BrProviderNames.NameMappings
    '            If nm.NameMappingSourceCol <> "PNParentNameFk" Then 'dont update parent as this upsets the tree
    '                Dim val As Object = GetConsensusValue(updatedPns, nm.NameMappingSourceCol)
    '                updateName(nm.NameMappingDestCol) = val
    '            End If
    '        Next

    '        'set rank string
    '        If Not updateName.IsNull("NameRankFk") Then
    '            For Each r As Rank In RankData.GetRanks()
    '                If r.IdAsInt = updateName("NameRankFk") Then
    '                    updateName("NameRank") = r.Name
    '                    Exit For
    '                End If
    '            Next
    '        End If

    '        'update name
    '        Dim uName As New Name(updateName, nameGuid)
    '        NameData.UpdateName(uName, SessionState.CurrentUser.Login)


    '        'update match scores
    '        For Each pn As DataRow In updatedPns.Tables(0).Rows
    '            Dim match As Integer = CalculateMatchScore(updateName, pn)
    '            NameData.UpdateProviderNameMatchScore(pn("PNPk"), match, SessionState.CurrentUser.Login)
    '            BrProviderNames.UpdateProviderNameAuthors(New ProviderName(pn, pn("PNPk").ToString))
    '        Next

    '        'update authors
    '        UpdateConsensusAuthors(uName)


    '        If includeConcepts Then
    '            RefreshNameConcepts(nameGuid)
    '        End If
    '    End Sub

    '    Public Shared Sub UpdateConsensusAuthors(ByVal updateName As Name)

    '        'update editor prov name authors?
    '        Dim sysPn As ProviderName = NameData.GetSystemProviderNameForName(updateName.Id)
    '        If sysPn IsNot Nothing AndAlso sysPn.PNLinkStatus <> LinkStatus.Discarded.ToString Then
    '            BrProviderNames.UpdateProviderNameAuthors(sysPn)
    '        End If

    '        'get majority authors from prov names (un corrected)

    '        Dim provNames As DataSet = NameData.GetProviderNameAuthors(updateName.Id)
    '        'update prov records to corrected values
    '        For Each row As DataRow In provNames.Tables(0).Rows
    '            If Not row.IsNull("PNABasionymAuthors") Then row("PNABasionymAuthors") = BrAuthors.GetCorrectedAuthors(row("PNABasionymAuthors").ToString)
    '            If Not row.IsNull("PNACombinationAuthors") Then row("PNACombinationAuthors") = BrAuthors.GetCorrectedAuthors(row("PNACombinationAuthors").ToString)
    '            If Not row.IsNull("PNABasExAuthors") Then row("PNABasExAuthors") = BrAuthors.GetCorrectedAuthors(row("PNABasExAuthors").ToString)
    '            If Not row.IsNull("PNACombExAuthors") Then row("PNACombExAuthors") = BrAuthors.GetCorrectedAuthors(row("PNACombExAuthors").ToString)
    '        Next

    '        Dim basVal As Object = GetConsensusValue(provNames, "PNABasionymAuthors").ToString
    '        Dim combVal As Object = GetConsensusValue(provNames, "PNACombinationAuthors").ToString
    '        Dim basExVal As Object = GetConsensusValue(provNames, "PNABasExAuthors").ToString
    '        Dim combExVal As Object = GetConsensusValue(provNames, "PNACombExAuthors").ToString

    '        'corrected author ids
    '        'Dim basAuth As String = BrAuthors.GetCorrectedAuthors(basVal.ToString)
    '        'Dim combAuth As String = BrAuthors.GetCorrectedAuthors(combVal.ToString)
    '        'Dim basEx As String = BrAuthors.GetCorrectedAuthors(basExVal.ToString)
    '        'Dim combEx As String = BrAuthors.GetCorrectedAuthors(combExVal.ToString)

    '        Dim nameAuth As DataSet = NameData.GetNameAuthors(updateName.Id)
    '        If nameAuth IsNot Nothing AndAlso nameAuth.Tables.Count > 0 AndAlso nameAuth.Tables(0).Rows.Count > 0 Then
    '            Dim ar As DataRow = nameAuth.Tables(0).Rows(0)
    '            NameData.InsertUpdateNameAuthor(ar("NameAuthorsPk"), updateName.Id, basVal, combVal, basExVal, combExVal, True, SessionState.CurrentUser.Login)
    '        Else
    '            NameData.InsertUpdateNameAuthor(-1, updateName.Id, basVal, combVal, basExVal, combExVal, True, SessionState.CurrentUser.Login)
    '        End If

    '        Dim fullAuth As String = BrAuthors.GetFullAuthorString(basVal, combVal, basExVal, combExVal, True)

    '        updateName.NameBasionymAuthors = BrAuthors.GetFullAuthorString(basVal, "", basExVal, "", False)
    '        updateName.NameCombinationAuthors = BrAuthors.GetFullAuthorString("", combVal, "", combExVal, False)
    '        updateName.NameAuthors = fullAuth

    '        NameData.UpdateName(updateName, SessionState.CurrentUser.Login)
    '    End Sub

    '    Public Shared Sub RefreshNameConcepts(ByVal nameGuid As String)
    '        Dim refreshedConcs As New ArrayList
    '        Dim refreshedCRs As New ArrayList

    '        Dim concs As DataSet = ConceptData.GetNameConceptRelationshipRecordsDs(nameGuid, True)

    '        For Each row As DataRow In concs.Tables(0).Rows
    '            If Not refreshedConcs.Contains(row("ConceptRelationshipConcept1Fk")) AndAlso _
    '                row("ConceptName1Fk").ToString = nameGuid Then
    '                BrConcepts.RefreshConceptData(row("ConceptRelationshipConcept1Fk"))
    '                refreshedConcs.Add(row("ConceptRelationshipConcept1Fk"))
    '            End If
    '            If Not refreshedConcs.Contains(row("ConceptRelationshipConcept2Fk")) AndAlso _
    '                row("ConceptToName1Fk").ToString = nameGuid Then
    '                BrConcepts.RefreshConceptData(row("ConceptRelationshipConcept2Fk"))
    '                refreshedConcs.Add(row("ConceptRelationshipConcept2Fk"))
    '            End If
    '            If Not refreshedCRs.Contains(row("ConceptRelationshipGuid")) Then
    '                BrConcepts.RefreshConceptRelationshipData(row("ConceptRelationshipGuid"))
    '                refreshedCRs.Add(row("ConceptRelationshipGuid"))
    '            End If
    '        Next
    '    End Sub

    '    ''' <summary>
    '    ''' Refresh all name fields that are links to other names.
    '    ''' Eg NamePreferred is updated to the NameFull of the Name pointed to by NamePreferredFk.
    '    ''' </summary>
    '    ''' <param name="nameGuid"></param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshNameLinkData(ByVal nameGuid As String)
    '        NameData.RefreshNameLinkData(nameGuid, SessionState.CurrentUser.Login)
    '    End Sub


    '    ''' <summary>
    '    ''' Refreshes all name data for the children of the specified name.
    '    ''' This will ensure that the NameParent links and details are up to date
    '    ''' </summary>
    '    ''' <param name="nameGuid"></param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshChildNames(ByVal nameGuid As String)
    '        Dim children As List(Of Name) = NameData.GetNameChildren(Nothing, nameGuid)
    '        For Each n As Name In children
    '            RefreshNameData(n.Id, True)
    '        Next
    '    End Sub

    '    ''' <summary>
    '    ''' Refreshes all names that need to be refreshed, ie the names that have an older updated date than
    '    ''' their provider names
    '    ''' </summary>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshAllNames(ByVal forceAll As Boolean)
    '        Try
    '            Cancel = False
    '            Dim names As DataSet
    '            If forceAll Then
    '                names = NameData.GetAllNamesForUpdate(Nothing)
    '            Else
    '                names = NameData.GetNamesForUpdate(Nothing)
    '            End If
    '            If StatusCallback IsNot Nothing Then StatusCallback.Invoke(1, "Updating names")

    '            Dim index As Integer = 1
    '            If names IsNot Nothing AndAlso names.Tables.Count > 0 Then
    '                For Each row As DataRow In names.Tables(0).Rows
    '                    Dim perc As Integer = index * 100 / names.Tables(0).Rows.Count

    '                    Try
    '                        RefreshNameData(row("NameGuid"), True)
    '                        RefreshNameLinkData(row("NameGuid"))
    '                    Catch ex As Exception
    '                        NamesException.LogError(ex)
    '                        If StatusCallback IsNot Nothing Then StatusCallback.Invoke(perc, "ERROR : Failed to update name " + row("NameFull").ToString + " (" + row("NameGuid").ToString + ")")
    '                    End Try

    '                    If perc > 99 Then perc = 99
    '                    If perc < 1 Then perc = 1
    '                    If StatusCallback IsNot Nothing Then StatusCallback.Invoke(perc, "Updating name " + index.ToString + " of " + names.Tables(0).Rows.Count.ToString)
    '                    index += 1
    '                    If Cancel Then Exit For
    '                Next
    '            End If

    '            If Cancel Then
    '                If StatusCallback IsNot Nothing Then StatusCallback.Invoke(100, "Cancelled")
    '            Else
    '                If StatusCallback IsNot Nothing Then StatusCallback.Invoke(100, "Complete")
    '            End If
    '        Catch ex As Exception
    '            NamesException.LogError(ex)
    '            If StatusCallback IsNot Nothing Then StatusCallback.Invoke(100, "Update failed")
    '        End Try

    '    End Sub

    '    ''' <summary>
    '    ''' Merges two names
    '    ''' Deletes the nameToMerge name and links all provider names that were to this name, to 
    '    ''' the nameToKeep
    '    ''' The nameToKeep is then refreshed so the merged provider data influences the name data
    '    ''' </summary>
    '    ''' <param name="nameToKeepId"></param>
    '    ''' <param name="nameToMergeId"></param>
    '    ''' <returns>The DataRow of the name to keep details before the merge</returns>
    '    ''' <remarks>
    '    ''' Any Concepts that linked to the old name will need to link to the new name.
    '    ''' Any children of the old name will need to point at the new name.
    '    ''' </remarks>
    '    Public Shared Function MergeNames(ByVal nameToKeepId As String, ByVal nameToMergeId As String) As DataRow
    '        Dim keepNameRow As DataRow
    '        Dim cnn As SqlClient.SqlConnection

    '        If NamesGlobal.DoLogging Then NamesException.LogMessage("Started Merge, " + DateTime.Now.ToString())

    '        Try
    '            cnn = New SqlClient.SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("compositae").ConnectionString)
    '            cnn.Open()

    '            'set all provider names for other name to this name
    '            NameData.RelinkProviderNames(Nothing, nameToMergeId, nameToKeepId, LinkStatus.Merge.ToString, SessionState.CurrentUser.Login)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Relinked Provider Names, " + DateTime.Now.ToString())

    '            'move any children of other name
    '            BrNames.MoveNameChildren(nameToMergeId, nameToKeepId, SessionState.CurrentUser.Login)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Moved Children of Merged Name, " + DateTime.Now.ToString())

    '            ConceptData.MergeNameConcepts(Nothing, nameToKeepId, nameToMergeId, SessionState.CurrentUser.Login)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Merged Concepts, " + DateTime.Now.ToString())

    '            Dim oldName As Name = NameData.GetName(Nothing, nameToMergeId)
    '            Dim keepName As Name = NameData.GetName(Nothing, nameToKeepId)

    '            keepNameRow = NameData.GetNameDs(Nothing, nameToKeepId).Tables(0).Rows(0)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Name LSIDs selected, " + DateTime.Now.ToString())

    '            'delete other name
    '            NameData.DeleteNameRecord(Nothing, oldName.NameLSID, keepName.NameLSID, SessionState.CurrentUser.Login)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Deleted other Name, " + DateTime.Now.ToString())

    '            'update associated concepts
    '            'ConceptData.UpdateConceptLinks(nameToMergeId, SessionState.CurrentUser.Login)
    '            'ConceptData.UpdateConceptLinks(nameToKeepId, SessionState.CurrentUser.Login)

    '            UpdateProviderConceptLinks(nameToMergeId)
    '            UpdateProviderConceptLinks(nameToKeepId)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Updated Concept Links to Megred Names, " + DateTime.Now.ToString())

    '            'refresh this names data
    '            RefreshNameData(nameToKeepId, True) ' SessionState.CurrentUser.Login)

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Refreshed Name Data, " + DateTime.Now.ToString())

    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Merge Complete, " + DateTime.Now.ToString())
    '        Catch ex As Exception
    '            If NamesGlobal.DoLogging Then NamesException.LogMessage("Merge Failed, " + DateTime.Now.ToString())

    '            Throw New NamesException("Failed to merge names : " + ex.Message)
    '        Finally
    '            If cnn IsNot Nothing Then cnn.Close()
    '        End Try

    '        Return keepNameRow
    '    End Function

    '    'update all provider concepts for the name to make sure they point to the correct consensus concepts
    '    Public Shared Sub UpdateProviderConceptLinks(ByVal nameGuid As String)
    '        Dim insPCRs As New ArrayList
    '        Dim provCR As DataSet = ConceptData.GetProviderConceptRelationshipRecords(nameGuid, True)

    '        For Each row As DataRow In provCR.Tables(0).Rows
    '            If Not insPCRs.Contains(row("PCRPk")) Then
    '                ConceptData.InsertConceptRelationshipFromProviderConceptRelationship(row("PCRPk"), SessionState.CurrentUser.Login)
    '                insPCRs.Add(row("PCRPk"))
    '            End If
    '        Next
    '    End Sub

    '    Public Shared Sub MoveNameChildren(ByVal fromNameGuid As String, ByVal toNameGuid As String, ByVal user As String)
    '        Dim children As List(Of Name) = NameData.GetChildNames(fromNameGuid, False)

    '        NameData.MoveNameChildren(Nothing, fromNameGuid, toNameGuid, user)

    '        'add system parent concept for each child name
    '        For Each cn As Name In children
    '            BrProviderConcepts.InsertUpdateSystemProviderConcept(cn.Id, toNameGuid, RelationshipType.RelationshipTypeParent, Nothing)
    '        Next
    '    End Sub

    '    'Public Shared Sub DeleteName(ByVal nameGuid As String)
    '    '    Dim cnn As SqlClient.SqlConnection
    '    '    Dim trans As SqlClient.SqlTransaction
    '    '    Try
    '    '        cnn = New SqlClient.SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("compositae").ConnectionString)
    '    '        cnn.Open()
    '    '        trans = cnn.BeginTransaction()

    '    '        'update provider names that pointed to this name to point to no name
    '    '        NameData.RelinkProviderNames(trans, nameGuid, Nothing, SessionState.CurrentUser.Login)

    '    '        'delete name
    '    '        ChecklistDataAccess.NameData.DeleteNameRecord(trans, nameGuid)

    '    '        trans.Commit()
    '    '    Catch ex As Exception
    '    '        If trans IsNot Nothing Then trans.Rollback()
    '    '        Throw New ChecklistException("Failed to delete name : " + ex.Message)
    '    '    Finally
    '    '        If cnn IsNot Nothing Then cnn.Close()
    '    '    End Try
    '    'End Sub

    '    ''' <summary>
    '    ''' Update Name that have the same basionym to point to the same preferred name 
    '    ''' This follows the principle that all names with the same basionym should be pointing to the 
    '    ''' same current name
    '    ''' </summary>
    '    ''' <param name="nameGuid"></param>
    '    ''' <param name="preferredNameGuid"></param>
    '    ''' <param name="accordingToFk"></param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub UpdateNamesWithSameBasionym(ByVal nameGuid As String, ByVal preferredNameGuid As String, ByVal accordingToFk As String)
    '        Dim names As List(Of Name) = NameData.GetNamesWithSameBasionym(nameGuid)

    '        For Each nm As Name In names
    '            If nm.Id <> nameGuid Then
    '                BrProviderConcepts.InsertUpdateSystemProviderConcept(nm.Id, preferredNameGuid, RelationshipType.RelationshipTypePreferred, accordingToFk)
    '            End If
    '        Next

    '    End Sub

    '    ''' <summary>
    '    ''' Get the provider concept for the specified name and accordingTo, for the specified provider
    '    ''' If the ProviderConcept doesnt exist, then Nothing is returned
    '    ''' </summary>
    '    ''' <param name="nameGuid"></param>
    '    ''' <param name="providerPk"></param>
    '    ''' <param name="accToFk"></param>
    '    ''' <returns></returns>
    '    ''' <remarks></remarks>
    '    Public Shared Function GetProviderConceptForName(ByVal nameGuid As String, ByVal providerPk As Integer, ByVal accToFk As String)
    '        Dim pc As ProviderConcept

    '        Dim accordingTo As String = ""
    '        If accToFk IsNot Nothing Then accordingTo = accToFk

    '        Dim conc As Concept
    '        Dim cs As DataSet = ConceptData.GetNameConceptsDs(nameGuid)
    '        For Each r As DataRow In cs.Tables(0).Rows
    '            If r("ConceptName1Fk").ToString = nameGuid And r("ConceptAccordingToFk").ToString = accordingTo Then

    '                Dim pcs As DataSet = ConceptData.GetProviderConceptRecords(r("ConceptPk"))
    '                For Each pcr As DataRow In pcs.Tables(0).Rows
    '                    If pcr("ProviderPk") = providerPk Then
    '                        pc = New ProviderConcept(pcr, pcr("PCPk").ToString)
    '                        Exit For
    '                    End If
    '                Next

    '                Exit For

    '            End If
    '        Next

    '        Return pc
    '    End Function

    '#End Region

    '#Region "References"

    '    ''' <summary>
    '    ''' Refreshes Reference record data
    '    ''' Update all Reference data from source ProviderReference records
    '    ''' </summary>
    '    ''' <param name="refIdList">ArrayList of ReferenceGuids for References to update</param>
    '    ''' <remarks></remarks>
    '    Public Shared Sub RefreshReferenceData(ByVal refIdList As ArrayList)
    '        For Each rId As String In refIdList
    '            'refresh Ref data
    '            ReferenceData.RefreshReferenceData(rId, SessionState.CurrentUser.Login)
    '        Next
    '    End Sub

    '    ''' <summary>
    '    ''' 
    '    ''' </summary>
    '    ''' <param name="refToMergeGuid"></param>
    '    ''' <param name="refToKeepGuid"></param>
    '    ''' <remarks></remarks>
    '    Public Shared Function MergeReferences(ByVal refToMergeGuid As String, ByVal refToKeepGuid As String) As DataRow
    '        Dim keepRefRow As DataRow
    '        Dim cnn As SqlClient.SqlConnection
    '        Dim trans As SqlClient.SqlTransaction
    '        Try
    '            cnn = New SqlClient.SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("compositae").ConnectionString)
    '            cnn.Open()
    '            trans = cnn.BeginTransaction()

    '            'set all provider names for other name to this name
    '            ReferenceData.RelinkProviderReferences(trans, refToMergeGuid, refToKeepGuid, LinkStatus.Merge.ToString, SessionState.CurrentUser.Login)

    '            'merge any concepts etc linking to the merged references
    '            ReferenceData.UpdateMergedReferenceLinks(trans, refToMergeGuid, refToKeepGuid, SessionState.CurrentUser.Login)


    '            Dim oldRef As DataSet = ReferenceData.GetReferenceDs(refToMergeGuid)
    '            Dim keepRef As DataSet = ReferenceData.GetReferenceDs(refToKeepGuid)
    '            keepRefRow = keepRef.Tables(0).Rows(0)

    '            'delete other ref
    '            ReferenceData.DeleteReferenceRecord(trans, oldRef.Tables(0).Rows(0)("ReferenceLsid").ToString, keepRef.Tables(0).Rows(0)("ReferenceLsid").ToString, SessionState.CurrentUser.Login)

    '            trans.Commit()
    '            trans = Nothing

    '            'refresh this names data
    '            ReferenceData.RefreshReferenceData(refToKeepGuid, SessionState.CurrentUser.Login)

    '        Catch ex As Exception
    '            If trans IsNot Nothing Then trans.Rollback()
    '            Throw New NamesException("Failed to merge names : " + ex.Message)
    '        Finally
    '            If cnn IsNot Nothing Then cnn.Close()
    '        End Try

    '        Return keepRefRow
    '    End Function
    '#End Region

End Class
